{% extends "base.html" %}

{% block title %}系统设置 - XCQuant{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">系统设置</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <!-- 基础设置 -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5>基础设置</h5>
                                </div>
                                <div class="card-body">
                                    <form id="basicSettingsForm">
                                        <div class="form-group">
                                            <label>系统名称</label>
                                            <input type="text" class="form-control" id="systemName" value="XCQuant">
                                        </div>
                                        <div class="form-group">
                                            <label>时区</label>
                                            <select class="form-control" id="timezone">
                                                <option value="Asia/Shanghai">Asia/Shanghai</option>
                                                <option value="UTC">UTC</option>
                                                <option value="America/New_York">America/New_York</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>日志级别</label>
                                            <select class="form-control" id="logLevel">
                                                <option value="DEBUG">DEBUG</option>
                                                <option value="INFO" selected>INFO</option>
                                                <option value="WARNING">WARNING</option>
                                                <option value="ERROR">ERROR</option>
                                            </select>
                                        </div>
                                        <button type="submit" class="btn btn-primary">保存基础设置</button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- 交易设置 -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5>交易设置</h5>
                                </div>
                                <div class="card-body">
                                    <form id="tradingSettingsForm">
                                        <div class="form-group">
                                            <label>默认交易所</label>
                                            <select class="form-control" id="defaultExchange">
                                                <option value="binance">Binance</option>
                                                <option value="okx">OKX</option>
                                            </select>
                                        </div>
                                        <div class="form-group">
                                            <label>最大持仓数量</label>
                                            <input type="number" class="form-control" id="maxPositions" value="10">
                                        </div>
                                        <div class="form-group">
                                            <label>风险控制级别</label>
                                            <select class="form-control" id="riskLevel">
                                                <option value="conservative">保守</option>
                                                <option value="moderate" selected>适中</option>
                                                <option value="aggressive">激进</option>
                                            </select>
                                        </div>
                                        <button type="submit" class="btn btn-primary">保存交易设置</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <!-- 通知设置 -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5>通知设置</h5>
                                </div>
                                <div class="card-body">
                                    <form id="notificationSettingsForm">
                                        <div class="form-group">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="emailNotification" checked>
                                                <label class="form-check-label" for="emailNotification">
                                                    邮件通知
                                                </label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label>邮件地址</label>
                                            <input type="email" class="form-control" id="emailAddress" placeholder="your@email.com">
                                        </div>
                                        <div class="form-group">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="wechatNotification">
                                                <label class="form-check-label" for="wechatNotification">
                                                    微信通知
                                                </label>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="telegramNotification">
                                                <label class="form-check-label" for="telegramNotification">
                                                    Telegram通知
                                                </label>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary">保存通知设置</button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- 系统信息 -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5>系统信息</h5>
                                </div>
                                <div class="card-body">
                                    <table class="table table-sm">
                                        <tr>
                                            <td><strong>版本:</strong></td>
                                            <td>1.0.0</td>
                                        </tr>
                                        <tr>
                                            <td><strong>启动时间:</strong></td>
                                            <td id="systemUptime">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Python版本:</strong></td>
                                            <td id="pythonVersion">-</td>
                                        </tr>
                                        <tr>
                                            <td><strong>数据库状态:</strong></td>
                                            <td><span class="badge badge-success">正常</span></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Redis状态:</strong></td>
                                            <td><span class="badge badge-success">正常</span></td>
                                        </tr>
                                    </table>
                                    
                                    <div class="mt-3">
                                        <button class="btn btn-warning btn-sm" onclick="restartSystem()">
                                            <i class="fas fa-redo"></i> 重启系统
                                        </button>
                                        <button class="btn btn-info btn-sm ml-2" onclick="exportConfig()">
                                            <i class="fas fa-download"></i> 导出配置
                                        </button>
                                        <button class="btn btn-secondary btn-sm ml-2" onclick="importConfig()">
                                            <i class="fas fa-upload"></i> 导入配置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 导入配置模态框 -->
<div class="modal fade" id="importConfigModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">导入配置</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>选择配置文件</label>
                    <input type="file" class="form-control-file" id="configFile" accept=".json,.yaml,.yml">
                </div>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    导入配置将覆盖当前设置，请确保配置文件正确。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="doImportConfig()">导入</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 页面加载时初始化
$(document).ready(function() {
    loadSystemInfo();
    loadSettings();
});

// 加载系统信息
function loadSystemInfo() {
    $.get('/api/system/info')
        .done(function(response) {
            if (response.success) {
                const info = response.data;
                $('#systemUptime').text(info.uptime || '-');
                $('#pythonVersion').text(info.python_version || '-');
            }
        })
        .fail(function() {
            console.error('无法加载系统信息');
        });
}

// 加载设置
function loadSettings() {
    $.get('/api/settings')
        .done(function(response) {
            if (response.success) {
                const settings = response.data;
                // 填充表单数据
                if (settings.basic) {
                    $('#systemName').val(settings.basic.system_name || 'XCQuant');
                    $('#timezone').val(settings.basic.timezone || 'Asia/Shanghai');
                    $('#logLevel').val(settings.basic.log_level || 'INFO');
                }
                if (settings.trading) {
                    $('#defaultExchange').val(settings.trading.default_exchange || 'binance');
                    $('#maxPositions').val(settings.trading.max_positions || 10);
                    $('#riskLevel').val(settings.trading.risk_level || 'moderate');
                }
                if (settings.notification) {
                    $('#emailNotification').prop('checked', settings.notification.email_enabled || false);
                    $('#emailAddress').val(settings.notification.email_address || '');
                    $('#wechatNotification').prop('checked', settings.notification.wechat_enabled || false);
                    $('#telegramNotification').prop('checked', settings.notification.telegram_enabled || false);
                }
            }
        })
        .fail(function() {
            console.error('无法加载设置');
        });
}

// 保存基础设置
$('#basicSettingsForm').on('submit', function(e) {
    e.preventDefault();
    
    const settings = {
        system_name: $('#systemName').val(),
        timezone: $('#timezone').val(),
        log_level: $('#logLevel').val()
    };
    
    $.post('/api/settings/basic', settings)
        .done(function(response) {
            if (response.success) {
                showSuccess('基础设置保存成功');
            } else {
                showError('保存失败: ' + response.error);
            }
        })
        .fail(function() {
            showError('网络错误，保存失败');
        });
});

// 保存交易设置
$('#tradingSettingsForm').on('submit', function(e) {
    e.preventDefault();
    
    const settings = {
        default_exchange: $('#defaultExchange').val(),
        max_positions: parseInt($('#maxPositions').val()),
        risk_level: $('#riskLevel').val()
    };
    
    $.post('/api/settings/trading', settings)
        .done(function(response) {
            if (response.success) {
                showSuccess('交易设置保存成功');
            } else {
                showError('保存失败: ' + response.error);
            }
        })
        .fail(function() {
            showError('网络错误，保存失败');
        });
});

// 保存通知设置
$('#notificationSettingsForm').on('submit', function(e) {
    e.preventDefault();
    
    const settings = {
        email_enabled: $('#emailNotification').is(':checked'),
        email_address: $('#emailAddress').val(),
        wechat_enabled: $('#wechatNotification').is(':checked'),
        telegram_enabled: $('#telegramNotification').is(':checked')
    };
    
    $.post('/api/settings/notification', settings)
        .done(function(response) {
            if (response.success) {
                showSuccess('通知设置保存成功');
            } else {
                showError('保存失败: ' + response.error);
            }
        })
        .fail(function() {
            showError('网络错误，保存失败');
        });
});

// 重启系统
function restartSystem() {
    if (confirm('确定要重启系统吗？这将中断所有正在运行的策略。')) {
        $.post('/api/system/restart')
            .done(function(response) {
                if (response.success) {
                    showSuccess('系统重启命令已发送');
                } else {
                    showError('重启失败: ' + response.error);
                }
            })
            .fail(function() {
                showError('网络错误，重启失败');
            });
    }
}

// 导出配置
function exportConfig() {
    window.location.href = '/api/settings/export';
}

// 导入配置
function importConfig() {
    $('#importConfigModal').modal('show');
}

// 执行导入配置
function doImportConfig() {
    const fileInput = document.getElementById('configFile');
    if (!fileInput.files.length) {
        showError('请选择配置文件');
        return;
    }
    
    const formData = new FormData();
    formData.append('config', fileInput.files[0]);
    
    $.ajax({
        url: '/api/settings/import',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                showSuccess('配置导入成功');
                $('#importConfigModal').modal('hide');
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                showError('导入失败: ' + response.error);
            }
        },
        error: function() {
            showError('网络错误，导入失败');
        }
    });
}

// 显示成功消息
function showSuccess(message) {
    // 可以使用toast或其他方式显示成功消息
    console.log(message);
    alert(message);
}

// 显示错误消息
function showError(message) {
    // 可以使用toast或其他方式显示错误
    console.error(message);
    alert(message);
}
</script>
{% endblock %}